<?php
class ReportIndexController  extends Zone_Action{
	protected function fields(){
		$data = array(
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),
			date_updated	=> array(
				type			=> 'NONE',
				default_value	=> mysql_date()
			),
			title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Tiêu đề'
			),
			status => array(
				type 	   => 'ENUM',
				no_empty   => true,
				value	   => array('active','inactive','complete','cancel'),
				form_label => 'Trạng thái'
			),
			rate => array(
				type 	   => 'INT',
				max		   => 100,
				min 	   => 0, 
				form_label => 'Tiến độ'
			),
			priority => array(
				type 	   	=> 'ENUM',
				value		=> array('0','1','2'),
				form_label 	=> 'Ưu tiên'
			),
			project_id => array(
				type 	   		=> 'INT',
				default_value	=> 0,
				form_label 		=> 'Dự án'
			),
			parent_id => array(
				type 	   		=> 'INT',
				default_value	=> 0,
				form_label 		=> 'Loại công việc'
			),
			desc => array(
				type 			=> 'HTML',
				default_value	=> '',
				form_label  	=> 'Mô tả'
			),
			date_start	=>array(
				type		=> 'DATE',
				fix_value	=> change_date_format, 
				no_empty	=> true,
				form_label 	=> 'Ngày bắt đầu'
			),
			date_end			=> array(
				type			=> 'DATE',
				fix_value		=> change_date_format, 
				form_label  	=> 'Ngày kết thúc',
				default_value	=> NULL	
			),
			time_start	=>array(
				type	=> 'CHAR',
				no_empty	=> true,
				form_label => 'Giờ bắt đầu'
			),
			time_end	=>array(
				type	=> 'CHAR',
				form_label => 'Giờ kết thúc',
				default_value	=> NULL	
			)
		);
		return $data;	
	}

	protected function fieldFile(){
		$data = array(
			files => array(
				type 	=> 'FILES',
				path	=> 'files/task/'
			)
		);
		return $data;	
	}
	
	public function initAction(){
		if(!$this->hasRole('task')){
			$this->setContent(error('Bạn không được phép truy cập phân hệ này'));	
			$this->stop();
		}	
		
		$this->set('task_groups',$this->Model->fetchAll("SELECT * FROM `tasks_types` ORDER BY `title`"));	
		$this->set('project_groups',$this->Model->fetchAll("SELECT * FROM `projects_types` ORDER BY `title`"));		
	}
	
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE
				`a`.`is_draft`='no'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}

	public function archiveAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`='complete'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`='complete'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Index/Archive?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
	
	
	public function groupAction(){
		$user_id = get_user_id();
		$parent_id = getInt('parent_id',0);
		
		$cat = $this->Model->fetchRow("SELECT * FROM `tasks_types` WHERE `ID`='$parent_id'");
		if( !$cat ){
			return $this->setJSON(array(
				content	=> error("Loại công việc đã bị xóa hoặc không tồn tại.")
			));
		}
		
		$this->set('cat',$cat);
		
		$vars = array(
			parent_id	=> $parent_id
		);		
		
		$where = array();
		
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`parent_id`='$parent_id'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`parent_id`='$parent_id'
				AND ( `c`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' )
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Index/Group?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}	
	
	public function guestAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`is_guest`='yes'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`					
			FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`			
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE				
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`is_guest`='yes'
				
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Index/Guest?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
		
	public function implementAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`is_implement`='yes'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`					
			FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`			
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`is_implement`='yes'
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Index/Implement?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}

	public function assignedAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);	
		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('is_read','title','created_by_id','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `a`.`created_by_id`='$user_id'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,		
				`u`.`is_deleted` as `created_is_deleted`		
			FROM  `tasks` as `a`
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `a`.`created_by_id`='$user_id'	
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Index/Assigned?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
	
	public function viewAction(){
		$task_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`c`.`username` as `updated_by_name`,
				`c`.`is_deleted` as `updated_is_deleted`,
				`d`.`title` as `project_title`,
				`e`.`title` as `parent_title`
			FROM `tasks` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c` 
				ON `a`.`updated_by_id`=`c`.`ID`				
			LEFT JOIN `projects` as `d` 
				ON `a`.`project_id`=`d`.`ID`
			LEFT JOIN `tasks_types` as `e` 
				ON `a`.`parent_id`=`e`.`ID`
			WHERE 
				`a`.`ID`='$task_id' LIMIT 1");			
		if( !$post ){
			return $this->setContent(error("Công việc đã bị xóa hoặc không tồn tại."));
		}
		
		if( $post['created_by_id'] != $user_id ){	
			$role = $this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `task_id`='$task_id' AND `user_id`='$user_id'");
			if( !$role ){
				return $this->setContent(error("Bạn không có quyền xem công việc này."));	
			}
		}
		
		$users = $this
			->Model->fetchAll("SELECT `a`.*,`b`.`is_guest`,`b`.`is_implement` 
				FROM `users` as `a` 
				LEFT JOIN `tasks_users` as `b`
					ON `b`.`user_id`=`a`.`ID` AND `b`.`task_id`='$task_id' 
				WHERE `b`.`task_id` IS NOT NULL");	
					
		$files	= $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
		
		if( !$this->Model->fetchRow("SELECT * FROM `tasks_reads` WHERE `task_id`='$task_id' AND `user_id`='$user_id'")){
			$this->Model->insert("tasks_reads",array(
				task_id		=>	$task_id,
				user_id		=>	$user_id,
				date_read 	=>	date("Y-m-d H:i:s")
			));	
		}		
		
		$ord = get('ord') == 'asc' ? 'ASC' : 'DESC';
		
		$comments = $this->Model->fetchAll("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`b`.`photo` as `created_by_photo` 
			FROM `tasks_comments` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			WHERE 
				`a`.`task_id`='$task_id' 
				AND `a`.`is_draft`='no'
			ORDER BY `date_created` $ord");
		
		foreach( $comments as $k => $p ){
			$comments[$k]['files'] = $this->Model->fetchAll("SELECT * 
				FROM `tasks_comments_files` WHERE `comment_id`='{$p['ID']}'");			
		}
		
		$this->set(array(
			comments 	=> $comments,
			users		=> $users,
			files		=> $files,	
			post 		=> $post
		));	
	}
		
	protected function checkData( $data, $form ){
		if( $data['date_end'] ){
			$date_start = strtotime($data['date_start']." ".$data['time_start'].":00");	
			$date_end   = strtotime($data['date_end']." ".$data['time_end'].":00");	
		
			if( $date_start >= $date_end ){
				$form->freeFile();
				return $data['date_end'].'Thời gian bắt đầu và kết thúc không hợp lí';
			}
			$data['date_start'] = $data['date_start']." ".$data['time_start'].":00";
			$data['date_end']	= $data['date_end']." ".$data['time_end'].":00";
			unset($data['time_start']);
			unset($data['time_end']);			
		}else{
			unset($data['date_end']);		
			unset($data['time_end']);		
			unset($data['time_start']);		
			$data['date_end'] = NULL;			
		}
		return $data;
	}
	
	public function uploadAction(){
		$this->removeLayout();		
		$user_id = get_user_id();		
		$task_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id'");
		if( !$post ){
			return $this->setJSON(array(
				alert	=> $task_id.'Công việc đã bị xóa hoặc không tồn tại.'
			));
		}

		if( $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert	=> 'Bạn không được phép tải tệp tin cho công việc này.'
			));	
		}			
	
		if( isPost() ){
			loadClass("ZData");
			$f = new ZData();

			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/task/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert("tasks_files",array(
					task_id			=> $task_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
						<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
						</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => $data
				));				
			}			
		}
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}

	//get projects can assign task
	protected function getProjects( $id='0' ){
		$project_id = get('project_id',0);
		$user_id = get_user_id();		
		
		$projects = $this->Model->fetchAll("SELECT `a`.*,
				IF( `a`.`ID`='$id',1,0) as `selected`
			FROM `projects` as `a`
			LEFT JOIN `projects_users` as `b` 
				ON `b`.`user_id`='$user_id' 
					AND `a`.`ID`=`b`.`project_id` 
					AND `b`.`is_supervisor`='yes'
			WHERE
				`a`.`status`='active'
				AND `a`.`is_draft`='no'
				AND `b`.`user_id`='$user_id'");
		return $projects;	
	}	
	
	protected function getTypes(){
		$this->set('types',$this->Model->fetchAll("SELECT * FROM `tasks_types` ORDER BY `title`"));		
	} 
	
	public function addAction(){
		$user_id = get_user_id();		
		$this->set('projects',$this->getProjects(get('project_id',0)));
		$this->getTypes();
		
		//check add task role for task normal	
		if( empty($_REQUEST['project_id']) ){
			if( !$this->hasRole('add_task') ){
				return $this->setContent(error('Bạn không có quyền giao việc thông thường.'));
			}
		
		}else{
			$project_id = get('project_id',0);
			$project = $this->Model->fetchRow("SELECT * 
				FROM `projects` WHERE `ID`='$project_id' AND `is_draft`='no'");
			if( !$project ){
				return $this->setJSON(array(
					alert	=> 'Dự án không tồn tại hoặc đã bị xóa'
				));
			}
			
			if( $project['status'] == 'inactive' ){
				return $this->setJSON(array(
					alert	=> 'Dự án đã tạm dừng'
				));	
			}

			if( $project['status'] == 'complete' ){
				return $this->setJSON(array(
					alert	=> 'Dự án đã kết thúc'
				));	
			}

			if( $project['status'] == 'cancel' ){
				return $this->setJSON(array(
					alert	=> 'Dự án đã hủy bỏ'
				));	
			}

			$project_role = $this->Model->fetchRow("SELECT * FROM `projects_users` 
				WHERE `user_id`='$user_id' AND `project_id`='$project_id'");
			if( !$project_role || $project_role['is_supervisor'] != 'yes'){
				return $this->setJSON(array(
					alert	=> 'Bạn không có quyền giao việc trong dự án này'
				));
			}	
		}		
		
		$post = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
		
		if( $post ){
			$task_id = $post['ID'];
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
			$users = $this
				->Model->fetchAll("SELECT `a`.*,`b`.* FROM `users` as `a` 
					LEFT JOIN `tasks_users` as `b`
					ON `b`.`user_id`=`a`.`ID` AND `b`.`task_id`='$task_id'");	
		}else{
			$this->Model->insert("tasks",array(
				is_draft		=> 'yes',
				created_by_id	=> $user_id
			));
			
			$task_id = $this->Model->lastId();
			$post 	 = array(
				ID	=> $task_id
			);
			$files   = array();	
			$users   = array();				
		}
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");		
		$this->set(array(
			user	=> $user,
			post	=> $post,
			files	=> $files,
			users	=> $users,
		));		

		if(isPost()){
			$this->removeLayout();
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields( $post ) );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data = $this->checkData( $data, $form );			
			if( !is_array($data) ){
				return $this->setJSON(array(
					'message'	=> error($data)
				));
			}
		
			$data['is_draft']='no';
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = date("Y-m-d H:i:s");
			$this->Model->update("tasks",$data,"`ID`='$task_id'");				
			$this->Model->delete("tasks_users","`task_id`='$task_id'");

			$roles = array();				
			$users = (array)$_POST['implement'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				$roles[$uid] = array(
					task_id	 	 => $task_id,
					user_id		 => $uid,
					is_implement => 'yes'
				);	
			}			
			
			$users = (array)$_POST['guest'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				if( isset( $roles[$uid]) ){
					$roles[$uid]['is_guest'] = 'yes';
				}else{
					$roles[$uid] = array(
						task_id		=> $task_id,
						user_id		=> $uid,
						is_guest	=> 'yes'
					);	
				}	
			}

			$this->Model->delete("tasks_users","`task_id`='$task_id'");
			foreach( $roles as $role ){
				$this->Model->insert('tasks_users',$role);
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $role['user_id'],
					url				=> "#Task/Index/View?ID=$task_id",
					title			=> $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> $role['is_implement'] =='yes' ?
						"Bạn được giao một công việc." : "Bạn được mời xem một công việc."
				));				
			}				

			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete("tasks_files","`ID`='{$f['ID']}'");
					@unlink("files/task/{$f['name']}");
				}
			}				
			
			$this->setJSON(array(
				redirect =>	"#Task/Index/View?ID=$task_id"
			));
		}		
	}

	public function editAction(){
		$this->getTypes();
		$user_id = get_user_id();		
		$task_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT `a`.*
				,`b`.`username` as `created_by_name` 
				,`b`.`is_deleted` as `created_is_deleted` 
			FROM `tasks` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`created_by_id`=`b`.`ID`
			WHERE `a`.`ID`='$task_id' AND `a`.`is_draft`='no'");

		if( $post && $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert	=> 'Chỉ người giao mới được sửa'
			));		
		}
		
		if( !$post ){
			return $this->setJSON(array(
				alert	=> 'Công việc đã bị xóa hoặc không tồn tại'
			));
		}	
		
		$this->set('projects',$this->getProjects($post['project_id']));

		$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
		$users = $this
			->Model->fetchAll("SELECT `b`.*,`a`.*
				FROM `users` as `a` 
				LEFT JOIN `tasks_users` as `b`
					ON `b`.`user_id`=`a`.`ID` AND `b`.`task_id`='$task_id'
				WHERE
					`b`.`task_id`='$task_id'");	
		
		$this->set(array(
			post	=> $post,
			files	=> $files,
			users	=> $users
		));
		
		if(isPost()){
			//check add task role for task normal	
			if( empty($_REQUEST['project_id']) ){
				if( !$this->hasRole('add_task') ){
					return $this->setContent(error('Bạn không có quyền giao việc thông thường.'));
				}
			//check task for project	
			}else{
				$project_id = get('project_id',0);
				$project = $this->Model->fetchRow("SELECT * 
					FROM `projects` WHERE `ID`='$project_id' AND `is_draft`='no'");
				if( !$project ){
					return $this->setJSON(array(
						alert	=> 'Dự án không tồn tại hoặc đã bị xóa'
					));
				}

				if( $project['status'] == 'complete' ){
					return $this->setJSON(array(
						alert	=> 'Dự án đã hoàn thành'
					));	
				}

				if( $project['status'] == 'inactive' ){
					return $this->setJSON(array(
						alert	=> 'Dự án đã tạm dừng'
					));	
				}				

				if( $project['status'] == 'cancel' ){
					return $this->setJSON(array(
						alert	=> 'Dự án đã hủy bỏ'
					));	
				}				
				
				$project_role = $this->Model->fetchRow("SELECT * FROM `projects_users` WHERE `user_id`='$user_id' AND `project_id`='$project_id'");
				if( !$project_role || $project_role['is_supervisor'] != 'yes'){
					return $this->setContent(error('Bạn không có quyền giao việc trong dự án này'));
				}			
			}		
			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields( $post ) );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data = $this->checkData( $data, $form );
			
			if( !is_array($data) ){
				return $this->setJSON(array(
					'message'	=> error($data)
				));
			}
		
			$data['is_draft']='no';
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = date("Y-m-d H:i:s");
			$this->Model->update("tasks",$data,"`ID`='$task_id'");				
			$this->Model->delete("tasks_users","`task_id`='$task_id'");

			$roles = array();				
			$users = (array)$_POST['implement'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				$roles[$uid] = array(
					task_id	 	 => $task_id,
					user_id		 => $uid,
					is_implement => 'yes'
				);	
			}			
			
			$users = (array)$_POST['guest'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				if( isset( $roles[$uid]) ){
					$roles[$uid]['is_guest'] = 'yes';
				}else{
					$roles[$uid] = array(
						task_id		=> $task_id,
						user_id		=> $uid,
						is_guest	=> 'yes'
					);	
				}	
			}

			$this->Model->delete("tasks_users","`task_id`='$task_id'");
			foreach( $roles as $role ){
				$this->Model->insert('tasks_users',$role);
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $role['user_id'],
					title			=> $data['title'],
					url				=> "#Task/Index/View?ID=$task_id",
					date			=> mysql_date(),
					content			=> "Công việc vừa được chỉnh sửa"
				));
			}				

			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete("tasks_files","`ID`='{$f['ID']}'");
					@unlink("files/task/{$f['name']}");
				}
			}				
			
			$this->setJSON(array(
				redirect =>	"#Task/Index/View?ID=$task_id"
			));			
		}
	}	

	public function deleteAction(){
		$this->removeLayout();
		$task_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id' AND `is_draft`='no'");

		if( !$post ){
			return $this->setJSON(array(
				alert => 'Công việc đã bị xóa hoặc không tồn tại'			
			));
		}
		
		if( $post && $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert => 'Chỉ người tạo công việc mới được xóa'			
			));
		}
	
		$this->Model->delete('tasks',"`ID`='$task_id'");
		
		$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
		$this->Model->delete("tasks_files","`task_id`='$task_id'");
		$this->Model->delete("tasks_users","`task_id`='$task_id'");
		$this->Model->delete("tasks_reads","`task_id`='$task_id'");
				
		foreach( $files as $file ){
			@unlink("files/task/{$file['name']}");
		}
				
		$comments = $this->Model->fetchAll("SELECT * FROM `tasks_comments` WHERE `task_id`='$task_id'");
		
		$this->Model->delete('tasks_comments',"`task_id`='$task_id'");
		
		foreach( $comments as $comment ){
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` WHERE `comment_id`='{$comment['ID']}'");
			foreach( $files as $file ){
				@unlink("files/task/{$file['name']}");
			}
		}
		
		return $this->setJSON(array(
			redirect => get('url_direct','#Task')
		));		
	}	
		
	public function updateAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$task_id = get("ID",0);
		
		$post = $this
			->Model->fetchRow("SELECT * FROM `tasks` 
				WHERE `is_draft`='no' AND `ID`='$task_id' AND `is_draft`='no'");

		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Công việc đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( $post['status'] == 'inactive' ){
			return $this->setJSON(array(
				alert	=> 'Công việc đang tạm dừng.'
			));		
		}		

		if( $post['status'] == 'complete' ){
			return $this->setJSON(array(
				alert	=> 'Công việc đã kết thúc.'
			));		
		}
		
		if( $post['created_by_id'] != $user_id ){		
			if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `user_id`='$user_id' AND `task_id`='$task_id' AND `is_implement`='yes'")  ){
				return $this->setJSON(array(
					alert	=> 'Chỉ người giao hoặc thực hiện mới được cập nhật tiến độ.'
				));		
			}
		}
		
		$this->set('post',$post);
		
		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();
			$f->addField(array(
				rate	=> array(
					type			=> 'INT',
					max				=> 100,
					min				=> 0,
					form_label		=> 'Tiến độ'
				)
			));
			
			$data = $f->getData();
		
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					message	=> error($data)
				));				
			}
			
			$this->Model->update('tasks',$data,"`ID`='$task_id'");
			
			$users = $this
				->Model->fetchAll("SELECT `a`.* 
					FROM `users` as `a` 
					LEFT JOIN `tasks_users` as `b` 
						ON `b`.`user_id`=`a`.`ID` AND `b`.`task_id`='$task_id' 
					WHERE `a`.`is_deleted`='no' AND `b`.`user_id`");
			
			foreach( $users as $user ){
				$this->Model->insert("notices",array(
					created_by_id	=> $user_id,
					user_id	=> $user['ID'],
					url		=> "#Task/Index/View?ID=$task_id",
					title	=> $post['title'],
					content	=> "Công việc vừa được cập nhật tiến độ: {$post['rate']} =&gt; {$data['rate']} %",
					date	=> mysql_date()
				));
			}
			
			$this->setJSON(array(
				redirect => "#Task/Index/View?ID=$task_id"
			));
		}	
	}
	
	public function statusAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$task_id = get("ID",0);
		
		$post = $this
			->Model->fetchRow("SELECT * FROM `tasks` 
				WHERE `is_draft`='no' AND `ID`='$task_id' AND `is_draft`='no'");

		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Công việc đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( $post['created_by_id'] != $user_id ){		
			return $this->setJSON(array(
				alert	=> 'Chỉ người giao mới được chuyển trạng thái.'
			));		
		}
		
		loadClass('ZData');
		$f = new ZData();
		$f->addField(array(
			status	=> array(
				type		=> 'ENUM',
				value		=> array('active','inactive','complete','cancel'),
				form_label	=> 'Trạng thái'
			)
		));
		
		$data = $f->getData();	
		if( !is_array( $data ) ){
			return $this->setJSON(array(
				alert	=> $data
			));				
		}
		
		if( $data['status'] =='complete' ){
			$data['rate'] = 100;
		}
		
		$this->Model->update('tasks',$data,"`ID`='$task_id'");		
		$users = $this
			->Model->fetchAll("SELECT `a`.* 
				FROM `users` as `a` 
				LEFT JOIN `tasks_users` as `b` 
					ON `b`.`user_id`=`a`.`ID` AND `b`.`task_id`='$task_id' 
				WHERE `a`.`is_deleted`='no' AND `b`.`user_id`");
		
		foreach( $users as $user ){
			$this->Model->insert("notices",array(
				created_by_id	=> $user_id,
				user_id	=> $user['ID'],
				url		=> "#Task/Index/View?ID=$task_id'",
				title	=> $post['title'],				
				content	=> "Công việc vừa được chuyển trạng thái.",
				date	=> mysql_date()
			));
		}
		
		$this->setJSON(array(
			redirect => "#Task/Index/View?ID=$task_id"
		));
	}	
	
	public function fileAction(){
		$this->removeLayout();
		$file_id = get('ID',0);
		$user_id = get_user_id();

		$file = $this->Model->fetchRow("SELECT * FROM `tasks_files` WHERE `ID`='$file_id'");

		if( !$file ){
			return $this->setError('404');
		}
		
		$task_id = $file['task_id'];
		$task = $this->Model->fetchRow("SELECT * FROM `tasks` WHERE `ID`='$task_id' LIMIT 1");		
		
		if( !$task ){
			return $this->setError('404');
		}
		
		if( $task['created_by_id'] != $user_id ){
			if( !$this->Model->fetchRow("SELECT * FROM `tasks_users` WHERE `task_id`='$task_id' AND `user_id`='$user_id' LIMIT 1")){
				return $this->setError('404');	
			}		
		}

		$file_path = "files/task/{$file['name']}";
		if( !file_exists( $file_path ) ){
			return $this->setError('404');
		}		
		if( get('type') == 'icon' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->resize(60, 60);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else if( get('type') == 'view' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else{
			@header("Content-Disposition: attachment; filename={$file['name']}");
			@readfile($file_path);
		}	
	}	
	
}	